const RefreshService = require('../service/refresh');
/**
 * @param {object} ctx
 */

async function refresh(ctx) {
  try {
    const { refreshToken } = ctx.request.body;

    if (!refreshToken) {
      throw { status: 400, message: 'Missing refresh token' };
    }

    const newAccessToken = await RefreshService.Refresh(refreshToken);

    if (newAccessToken) {
      const responseData = {
        code: 201,
        msg: '刷新成功',
        data: { accessToken: newAccessToken },
      };
      ctx.body = responseData;
    } else {
      throw { status: 401, message: '刷新失败' };
    }
  } catch (error) {
    throw error;
  }
}

module.exports = { refresh };
